package com.yj.springbootstudy.algorithm.topic;

import lombok.Data;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 二叉树
 */
public class Demo02 {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(2);
        TreeNode left = new TreeNode(1);
        TreeNode right = new TreeNode(3);
        root.setLeft(left);
        root.setRight(right);
        BinaryTree binaryTree = new BinaryTree(root);
        binaryTree.front(root);
        System.out.println(root);
        binaryTree.center(root);
        System.out.println(root);
        binaryTree.rear(root);
        System.out.println(root);
        binaryTree.level(root);
    }
}

class BinaryTree{

    private TreeNode root;

    public BinaryTree(TreeNode root){
        this.root = root;
    }

    //前序遍历
    public void front(TreeNode root){
        System.out.println(root.getData());
        if (root.getLeft()!=null){
            front(root.getLeft());
        }
        if (root.getRight()!=null){
            front(root.getRight());
        }
    }

    //中序遍历
    public void center(TreeNode root){
        if (root.getLeft()!=null){
            center(root.getLeft());
        }
        System.out.println(root.getData());
        if (root.getRight()!=null){
            center(root.getRight());
        }
    }

    //后续遍历
    public void rear(TreeNode root){
        if (root.getLeft()!=null){
            rear(root.getLeft());
        }
        if (root.getRight()!=null){
            rear(root.getRight());
        }
        System.out.println(root.getData());
    }

    // 层次遍历
    public void level(TreeNode root){

        if (root == null) {
            return;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);

        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            System.out.print(node.getData() + "->");

            if (node.getLeft() != null) {
                queue.add(node.getLeft());
            }
            if (node.getRight() != null) {
                queue.add(node.getRight());
            }
        }
    }




}

@Data
class TreeNode{
    private int data;
    private TreeNode left;
    private TreeNode right;

    public TreeNode(int data){
        this.data = data;
    }
}
